import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ncsjqz_getx/page/home/home_view.dart';
import 'package:flutter_ncsjqz_getx/util/assets_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_ncsjqz_getx/widget/gradient_button.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/input_widget.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

import 'login_logic.dart';

/// <summary>
/// author：zwb
/// dateTime： 2022/1/4 09:29
/// filePath： lib/page/login/login_view.dart
/// desc: 登录页面
/// <summary>
///
class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final logic = Get.put(LoginLogic());
  StreamSubscription<BaseWeChatResponse>? streamSubscription;
  int wxUserId = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    streamSubscription = weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is WeChatAuthResponse) {
        int errCode = res.errCode;
        print('微信登录返回值：ErrCode :$errCode  code:${res.code}');
        if (errCode == 0) {
          // streamSubscription!.cancel();
          logic.onLogin(isWx: true,code: res.code);
        } else if (errCode == -4) {
          toast("用户拒绝授权");
        } else if (errCode == -2) {
          toast("用户取消授权");
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: GetBuilder<LoginLogic>(
          builder: (controller) {
            return Stack(
              children: [
                buildBgWidget(),
                buildInputPan(),
                Positioned(
                  bottom: 50,
                  child: buildBottomBtn(),
                ),
              ],
            );
          },
        ),
      ),
      onWillPop: () async {
        /// 回到商城主页
        Get.off(()=>HomePage());
        return false;
      },
    );
  }

  @override
  void dispose() {
    Get.delete<LoginLogic>();
    streamSubscription!.cancel();
    super.dispose();
  }

  /// todo：背景
  buildBgWidget(){
    return Container(
      height: Get.height,
      width: Get.width,
      alignment: Alignment.topCenter,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(getLocalImg("login_bg.png")),
          alignment: Alignment.topCenter,
        ),
      ),
    );
  }

  /// todo：输入面板
  buildInputPan() {
    return Container(
      padding: EdgeInsets.all(15),
      child:  Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          !logic.loginRegister ? InkWidget.title("注册账号",fonSize: 16):Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWidget.title(logic.loginType == 1 ?"账号密码登陆":"验证码登陆",fonSize: 16),
              // InkWidget.text("忘记密码？",color: Colors.green,onTap: (){
              //   // Get.to(()=>GetPasswordPage());
              //   Get.to(()=>EmailPhonePasswordPage(title: "忘记密码",type: EPW.getPwd,emailPhone: ""));
              // }),
            ],
          ),
          SizedBox(height: 20,),
          logic.loginRegister ? loginPan() : regPan(),
          SizedBox(height: 20,),
          Center(
            child: SizedBox(
              width: Get.width * 0.6,
              child: gradientButton(logic.loginRegister ?"登 录":"注 册",circular: 40,onTap: (){
                if(logic.textEditingControllerTel.text == "")return toast("请输入手机号");
                if(logic.textEditingControllerTel.text.length != 11)return toast("手机号不正确");
                logic.loginRegister ? logic.onLogin():  logic.onRegister();
              }),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(
              vertical: 20,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // Row(
                //   children: [
                //     InkWidget.text(!logic.loginRegister ?"已有账号，":"还没有账号，"),
                //     InkWidget.text(!logic.loginRegister ?"马上登录":"马上注册",color: Colors.green,onTap: (){
                //       logic.setLoginRegister();
                //     }),
                //   ],
                // ),
                // InkWidget.text(logic.loginType != 1 ?"账号密码登陆":"验证码登陆",color: Colors.green,onTap: (){
                //   logic.setLoginType();
                // }),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// todo：第三方+隐私协议
  buildBottomBtn() {
    return Container(
      width: Get.width,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWidget.title("第三方登录\n",fonSize: 16,),
          InkWidget.imgAsset("wx.png",width: 50,onTap: () async{
            if (!logic.checkProtocol) return toast("请阅读并同意勾选《用户协议》和《隐私政策》");
            isWeChatInstalled.then((value) {
              if (!value) {
                toast("当前设备未安装微信");
                return;
              }
              sendWeChatAuth( scope: "snsapi_userinfo", state: "wechat_sdk_demo_test");
            });
          }),
          SizedBox(height: 10,),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              InkWell(
                child: Icon(logic.checkProtocol?Icons.check_box:Icons.check_box_outline_blank,color: Colors.green,size: 20,),
                onTap: (){
                  setState(() {
                    logic.checkProtocol = !logic.checkProtocol;
                  });
                },
              ),
              InkWidget.text("\n已阅读",height: 0.5,color: Colors.grey,),
              InkWidget.text("\n《用户协议》",height: 0.5,color: Colors.green,onTap: (){
                logic.getProtocol("用户协议");
              }),
              InkWidget.text("\n和",height: 0.5,color: Colors.grey,),
              InkWidget.text("\n《隐私政策》",height: 0.5,color: Colors.green,onTap: (){
                logic.getProtocol("隐私政策");
              }),
            ],
          ),
        ],
      ),
    );
  }

  /// todo：登录面板
  loginPan() {
    return Column(
      children: [
        textFieldWidget(
          hintText: "请输入您的手机号",
          inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
          ],
          keyboardType: TextInputType.phone,
          maxLength: 11,
          controller: logic.textEditingControllerTel,
          prefixIcon: InkWidget.imgAsset("my_select.png",padding: EdgeInsets.all(10),),
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        logic.loginType == 1?
        textFieldWidget(
          hintText: "请输入您的密码",
          controller: logic.textEditingControllerPwd,
          prefixIcon: InkWidget.imgAsset("pwd.png",padding: EdgeInsets.all(10,),),
          suffixIcon: InkWidget.imgAsset(
            !logic.showPwd ? "yj.png": "by.png",
            onTap: (){
              logic.setShowPwd();
            },
            width: 20,
            padding: EdgeInsets.all(10,),
          ),
          obscureText: logic.showPwd,
          maxLines: 1,
          circular: 5,
          height: 40,
        ) : textFieldWidget(
          hintText: "请输入验证码",
          controller: logic.textEditingControllerCode,
          inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
          ],
          keyboardType: TextInputType.number,
          suffixIcon: gradientButton(logic.getTimeDown!=60 ?"${logic.getTimeDown}" :"发送验证码",onTap:logic.getTimeDown!=60 ?null: (){
            logic.codeType = 2;
            logic.sendAuthCode();
          }),
          obscureText: logic.showPwd,
          maxLines: 1,
          circular: 5,
          height: 40,
        ),
      ],
    );
  }

  /// todo：注册面板
  regPan() {
    return Column(
      children: [
        textFieldWidget(
          hintText: "请输入您的手机号",
          controller: logic.textEditingControllerTel,
          inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
          ],
          keyboardType: TextInputType.phone,
          maxLength: 11,
          prefixIcon: InkWidget.imgAsset("my_select.png",padding: EdgeInsets.all(10),),
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        textFieldWidget(
          hintText: "请输入验证码",
          controller: logic.textEditingControllerCode,
          suffixIcon: gradientButton(logic.getTimeDown!=60 ?"${logic.getTimeDown}" :"发送验证码", onTap: logic.getTimeDown!=60 ?null:(){
            logic.codeType = 1;
            logic.sendAuthCode();
          }),
          obscureText: logic.showPwd,
          maxLines: 1,
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        textFieldWidget(
          hintText: "请输入您的密码",
          controller: logic.textEditingControllerPwd,
          prefixIcon: InkWidget.imgAsset("pwd.png",padding: EdgeInsets.all(10,),),
          obscureText: true,
          maxLines: 1,
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        textFieldWidget(
          hintText: "请再次确认您的密码",
          controller: logic.textEditingControllerPwd1,
          prefixIcon: InkWidget.imgAsset("pwd.png",padding: EdgeInsets.all(10,),),
          obscureText: true,
          maxLines: 1,
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        textFieldWidget(
          hintText: "请输入您所居住的地区",
          controller: logic.textEditingControllerAddress,
          prefixIcon: InkWidget.imgAsset("location.png",padding: EdgeInsets.all(10,),),
          maxLines: 1,
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        textFieldWidget(
          hintText: "请输入您的出生年月日",
          controller: logic.textEditingControllerBirthday,
          prefixIcon: InkWidget.imgAsset("sr.png",padding: EdgeInsets.all(10,),),
          maxLines: 1,
          circular: 5,
          height: 40,
        ),
        SizedBox(height: 20,),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            MaterialButton(
              onPressed: (){
                logic.setSex(2);
              },
              child: Row(
                children: [
                  InkWidget.imgAsset(logic.sex == 2 ? "select.png": "uselect.png",width: 15),
                  InkWidget.text("  我是女生"),
                ],
              ),
              color: Colors.grey.shade200,
              elevation: 0,
            ),

            MaterialButton(
              onPressed: (){
                logic.setSex(1);
              },
              child: Row(
                children: [
                  InkWidget.imgAsset(logic.sex == 1 ? "select.png": "uselect.png",width: 15),
                  InkWidget.text("  我是男生"),
                ],
              ),
              color: Colors.grey.shade200,
              elevation: 0,
            ),
          ],
        )
      ],
    );
  }
}